from django.db import models
from django.db.models import Sum, Count, Max
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from assets.thumbs import ImageWithThumbsField

from cache import model_property_cache

from assets.models import Asset
from files.models import File

from tags.models import TaggedObject, TagType

from ratings.models import Rating

class Profile(models.Model):
  user = models.OneToOneField(User, related_name='data')
  signature = models.CharField(max_length=256)
  #avatar = models.ImageField(upload_to='avatars/%Y/%m/%d')
  avatar = ImageWithThumbsField(upload_to='avatars/%Y/%m/%d', sizes=((150,150),))
  
  class Meta:
    db_table = 'Profiles'
    verbose_name_plural = "Profiles"
  
  @property
  @model_property_cache
  def nr_of_assets(self):
    return Asset.objects.filter(file__author=self.user).count()
  
  @property
  def topassets(self):
    type = ContentType.objects.get_for_model(Asset)
    qs = Asset.objects.filter(file__author=self.user).extra(select={
    'total': """
        SELECT SUM(rating) AS total
        FROM ratings_rating
        WHERE 
            content_type_id=%s AND
            object_id=CAST(Assets.id as CHAR(400))
        """
    },
    select_params=[type.pk],
    order_by=['-total'])
    return qs[:3]
  
  @property
  def tag_cloud(self):
    type = ContentType.objects.get_for_model(Asset)
    assets = Asset.objects.filter(file__author=self.user).values_list('id', flat=True)
    tags = TagType.objects.filter(taggedobject__content_type=type, taggedobject__object_id__in=assets).annotate(count=Count('id'))
    max = tags.aggregate(r=Max('count'))['r']
    averaged = []
    for tag in tags[:15]:
      averaged.append({'id':tag.id,'category':tag.category,'type':tag.type,'size': (tag.count / max)+1})
    return averaged
    
    
  @property
  def recentuploads(self): 
    return File.objects.filter(author=self.user).order_by('-stamp')[:5]
    
    
  def __unicode__(self):
    return '%s - %s'%(self.id, self.user.username)


User.profile = property(lambda u: Profile.objects.get_or_create(user=u, defaults={'signature': 'sueastside rocks!'})[0])
